'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';

interface Product {
  id: number;
  name: string;
  description: string | null;
  price: number;
  sku: string | null;
  imageUrl: string | null;
  category: string | null;
  createdAt: string;
  updatedAt: string;
}

interface Inventory {
  id: number;
  productId: number;
  quantity: number;
  lowStockThreshold: number;
  updatedAt: string;
}

export default function ProductDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const [resolvedParams, setResolvedParams] = useState<{ id: string } | null>(null);
  const [product, setProduct] = useState<Product | null>(null);
  const [inventory, setInventory] = useState<Inventory | null>(null);
  const [loading, setLoading] = useState(true);
  const router = useRouter();
  const searchParams = useSearchParams();
  
  // 获取来源页面信息
  const fromOrder = searchParams?.get('from') === 'order';
  const orderId = searchParams?.get('orderId');

  useEffect(() => {
    async function resolveParams() {
      const resolved = await params;
      setResolvedParams(resolved);
    }
    resolveParams();
  }, [params]);

  useEffect(() => {
    if (resolvedParams) {
      fetchProduct();
      fetchInventory();
    }
  }, [resolvedParams]);

  const fetchProduct = async () => {
    if (!resolvedParams) return;
    
    try {
      const response = await fetch(`/api/products/${resolvedParams.id}`);
      if (!response.ok) {
        throw new Error('获取产品信息失败');
      }
      const productData = await response.json();
      setProduct(productData);
    } catch (error) {
      console.error('获取产品详情失败:', error);
    }
  };

  const fetchInventory = async () => {
    if (!resolvedParams) return;
    
    try {
      // 先获取所有库存，然后过滤
      const inventoryResponse = await fetch('/api/inventory');
      if (inventoryResponse.ok) {
        const inventoryData = await inventoryResponse.json();
        const productInventory = inventoryData.find((inv: any) => inv.productId === parseInt(resolvedParams.id));
        if (productInventory) {
          setInventory(productInventory);
        }
      }
    } catch (error) {
      console.error('获取库存信息失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    if (!product || !confirm('确定要删除这个产品吗？此操作不可恢复。')) return;
    
    try {
      const response = await fetch(`/api/products/${product.id}`, {
        method: 'DELETE',
      });

      if (!response.ok) {
        throw new Error('删除产品失败');
      }

      router.push('/products');
    } catch (error) {
      console.error('删除产品失败:', error);
      alert('删除产品失败，请重试');
    }
  };

  if (loading) return <div className="p-8">加载中...</div>;
  if (!product) return <div className="p-8">产品不存在</div>;

  const isLowStock = inventory && inventory.quantity <= inventory.lowStockThreshold;

  return (
    <div className="p-8">
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          {fromOrder && orderId ? (
            <Link 
              href={`/orders/${orderId}`}
              className="text-gray-600 hover:text-gray-900"
            >
              ← 返回订单 #{orderId}
            </Link>
          ) : (
            <Link href="/products" className="text-gray-600 hover:text-gray-900">
              ← 返回产品列表
            </Link>
          )}
          <h1 className="text-3xl font-bold">产品详情</h1>
        </div>
        
        <div className="flex items-center space-x-3">
          <Link
            href={`/products/edit/${product.id}`}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
          >
            编辑产品
          </Link>
          <button
            onClick={handleDelete}
            className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
          >
            删除产品
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 产品信息 */}
        <div className="bg-white rounded-lg shadow p-6">
          <h2 className="text-xl font-semibold mb-4">产品信息</h2>
          
          <div className="space-y-4">
            <div>
              <div className="text-sm text-gray-600">产品名称</div>
              <div className="text-lg font-semibold">{product.name}</div>
            </div>

            {product.description && (
              <div>
                <div className="text-sm text-gray-600">产品描述</div>
                <div className="text-sm">{product.description}</div>
              </div>
            )}

            <div>
              <div className="text-sm text-gray-600">价格</div>
              <div className="text-2xl font-bold text-blue-600">¥{product.price.toLocaleString()}</div>
            </div>

            {product.sku && (
              <div>
                <div className="text-sm text-gray-600">SKU</div>
                <div className="text-sm font-mono">{product.sku}</div>
              </div>
            )}

            {product.category && (
              <div>
                <div className="text-sm text-gray-600">分类</div>
                <div className="text-sm">{product.category}</div>
              </div>
            )}

            {product.imageUrl && (
              <div>
                <div className="text-sm text-gray-600 mb-2">产品图片</div>
                <img
                  src={product.imageUrl}
                  alt={product.name}
                  className="w-32 h-32 object-cover rounded-md"
                />
              </div>
            )}
          </div>
        </div>

        {/* 库存信息 */}
        <div className="bg-white rounded-lg shadow p-6">
          <h2 className="text-xl font-semibold mb-4">库存信息</h2>
          
          {inventory ? (
            <div className="space-y-4">
              <div>
                <div className="text-sm text-gray-600">当前库存</div>
                <div className={`text-2xl font-bold ${isLowStock ? 'text-red-600' : 'text-green-600'}`}>
                  {inventory.quantity} 件
                </div>
                {isLowStock && (
                  <div className="text-sm text-red-600 mt-1">
                    库存不足！低于阈值 {inventory.lowStockThreshold}
                  </div>
                )}
              </div>

              <div>
                <div className="text-sm text-gray-600">低库存阈值</div>
                <div className="text-sm">{inventory.lowStockThreshold} 件</div>
              </div>

              <div>
                <div className="text-sm text-gray-600">最后更新</div>
                <div className="text-sm">
                  {new Date(inventory.updatedAt).toLocaleString('zh-CN')}
                </div>
              </div>
            </div>
          ) : (
            <div className="text-center text-gray-500 py-8">
              <div className="text-lg mb-2">暂无库存信息</div>
              <Link
                href={`/inventory?productId=${product.id}`}
                className="text-blue-600 hover:text-blue-800"
              >
                管理库存
              </Link>
            </div>
          )}
        </div>

        {/* 元数据 */}
        <div className="bg-white rounded-lg shadow p-6 lg:col-span-2">
          <h2 className="text-xl font-semibold mb-4">元数据</h2>
          
          <div className="grid grid-cols-2 gap-4">
            <div>
              <div className="text-sm text-gray-600">创建时间</div>
              <div className="text-sm">
                {new Date(product.createdAt).toLocaleString('zh-CN')}
              </div>
            </div>

            <div>
              <div className="text-sm text-gray-600">最后更新</div>
              <div className="text-sm">
                {new Date(product.updatedAt).toLocaleString('zh-CN')}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}